# -*- coding: utf-8 -*-
import tornado.escape
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.options
import time
import logging
import uuid
from apps.utils import Utils
from apps.plugins.pipeline import Pipeline

pipeline = Pipeline()


class WebSocketSever(tornado.websocket.WebSocketHandler):
    bao_cons = set()
    bao_waiters = {}
    global con_key

    clients = {}

    async def open(self, *args):
        self.sn = self.get_argument('sn', default='')
        self.token = self.get_argument('token', default='')

        if Utils.is_null(self.sn):
            self.close()
            return
            
        logging.info(self.sn)

        self.clients[self.sn] = {"sn": self.sn, "object": self}
        logging.info("websocket opened! sn:" + self.sn)

    def on_message(self, message):
        if message == "close":
            self.close()
            return

        # 发送一个管道消息到 客户端服务器
        data = '{"cmd":"ssh", "sn": "%s", "command": "%s"}' % (self.sn,
                                                               message)
        pipeline.send_data(data)


    def check_origin(self, origin):
        # 此处用于跨域访问
        return True

    def allow_draft76(self):
        return True

    def on_close(self):
        if self.sn in self.clients:
            del self.clients[self.sn]
            logging.info("websocket closed!")
